<script setup name="ScoreOverviewProceed">
import { ref, shallowRef, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElTable, ElTableColumn, ElPagination, ElSelect, ElOption, ElMessage } from 'element-plus';
import { Download, Search } from '@element-plus/icons-vue';
import service from '@/utils/request';

const router = useRouter();
const searchRef = ref(null);
const searchValue = ref(''); // 搜索值
const totalData = ref({ fine: 0, qualify: 0, notQualify: 0 });
const tableData = ref([]);
const pageNum = shallowRef(1);
const totalSize = shallowRef(0);
const pageSize = shallowRef(5);
const exportLoading = shallowRef(false);
const tableLoading = shallowRef(false); // 添加表格加载状态

// 处理表格数据
const fixedTableData = (list) => {
  if (!list || !Array.isArray(list)) return [];
  return list.map((item) => ({
    examId: item.examId,
    name: item.username,
    jobId: item.jobId,
    taskName: item.name,
    taskState: item.state,
    baseWorkScore: item.baseWorkScore,
    outstandingWorkScore: item.academicWorkScore,
    sumScore: item.sumScore,
    examResult: item.result
  }));
};

// 获取表格数据
const getTableData = async (key) => {
  try {
    tableLoading.value = true;
    const res = await service({
      method: "get",
      url: "/superadmin/score/select",
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token'),
      },
      params: {
        state: "进行中",
        condition: key,
        years: "",
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    });

    // 重置数据状态
    if (!res.data?.scoreResults?.list) {
      tableData.value = [];
      totalData.value = { fine: 0, qualify: 0, notQualify: 0 };
      totalSize.value = 0;
      return;
    }

    tableData.value = fixedTableData(res.data.scoreResults.list);
    totalSize.value = res.data.scoreResults.total || 0;
  } catch (error) {
    //console.error('获取表格数据失败:', error);
    ElMessage({
      message: '获取数据失败，请稍后重试',
      type: 'error'
    });
    tableData.value = [];
    totalData.value = { fine: 0, qualify: 0, notQualify: 0 };
    totalSize.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 导出功能
const exportClick = async () => {
  try {
    exportLoading.value = true;
    const res = await service({
      method: "get",
      url: "/superadmin/score/export",
      headers: {
        Authorization: localStorage.getItem('token'),
      },
      params: {
        state: "进行中",
        years: "",
        condition: searchValue.value,
      },
      responseType: 'blob'
    });

    const blob = new Blob([res.data]);
    const fileName = `成绩导出_${new Date().toLocaleDateString()}.xlsx`;
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    // 清理
    setTimeout(() => {
      document.body.removeChild(elink);
      URL.revokeObjectURL(elink.href);
    }, 100);

    ElMessage({
      message: '导出成功',
      type: 'success'
    });
  } catch (error) {
    ElMessage({
      message: '导出失败，请稍后重试',
      type: 'error'
    });
  } finally {
    exportLoading.value = false;
  }
};

// 点击详情
const operationClick = (row, column) => {
  if (column.property !== 'operation') return;
  router.push({
    path: '/superAdministrator/scoreOverview/proceed/detail',
    query: row
  });
};

// 分页处理
const handleSizeChange = (newPageNum) => {
  pageNum.value = newPageNum;
  getTableData(searchValue.value);
};

// 每页条数变化
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  pageNum.value = 1; // 重置到第一页
  getTableData(searchValue.value);
};

// 搜索处理
const searchChange = () => {
  pageNum.value = 1; // 搜索时重置到第一页
  getTableData(searchValue.value);
};

// 组件挂载时获取数据
onMounted(() => {
  getTableData('');
});
</script>

<template>
  <div class="scoreOverviewProceed">
    <!-- 总体数据 -->
    <div class="totalData">
      <div class="layout">
        <div class="content">
          <div class="icon">
            <span class="iconfont icon-youxiuxuesheng"></span>
          </div>
          <div class="text">
            <div class="title">优秀人数</div>
            <div class="value">{{ totalData.fine }}</div>
          </div>
        </div>
        <div class="content">
          <div class="icon">
            <span class="iconfont icon-buhuanhegebiaozhi"></span>
          </div>
          <div class="text">
            <div class="title">合格人数</div>
            <div class="value">{{ totalData.qualify }}</div>
          </div>
        </div>
        <div class="content">
          <div class="icon">
            <span class="iconfont icon-yewu_buhege"></span>
          </div>
          <div class="text">
            <div class="title">不合格人数</div>
            <div class="value">{{ totalData.notQualify }}</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="dataTable">
      <div class="tableHeader">
        <div class="left">
          <span>2024-2025学年突出工作情况</span>
        </div>
        <div class="right">
          <div class="search" ref="searchRef">
            <input 
              v-model="searchValue" 
              type="text" 
              placeholder="搜索" 
              @keyup.enter="searchChange"
            />
            <el-icon class="icon" @click="searchChange"><Search /></el-icon>
          </div>
          <div 
            class="export" 
            @click="exportClick"
            :class="{ 'export-disabled': exportLoading }"
          >
            <span>导出</span>
            <el-icon :size="18"><Download /></el-icon>
          </div>
        </div>
      </div>
      
      <div class="tableContent"
        v-loading="tableLoading || exportLoading"
        element-loading-text="正在处理..."
      >
        <el-table 
          :data="tableData"
          :style="{width: '100%'}"
          height="100%"
          show-overflow-tooltip
          :header-cell-style="{ color: '#000', background: '#f2f3f5' }"
          empty-text="暂无数据"
          @cell-click="operationClick"
        >
          <el-table-column align="left" prop="name" label="姓名" width="130"></el-table-column>
          <el-table-column align="center" prop="jobId" label="工号" width="90"></el-table-column>
          <el-table-column align="left" prop="taskName" label="考核名称"></el-table-column>
          <el-table-column align="center" prop="taskState" label="任务状态" width="90">
            <template #default="scope">
              <span :class="`status-${scope.row.taskState}`">{{ scope.row.taskState }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="baseWorkScore" label="基本工作得分" width="110"></el-table-column>
          <el-table-column align="center" prop="outstandingWorkScore" label="突出工作得分" width="110"></el-table-column>
          <el-table-column align="center" prop="sumScore" label="总得分" width="90"></el-table-column>
          <el-table-column align="center" prop="examResult" label="考核结果" width="90">
            <template #default="scope">
              <span :class="`result-${scope.row.examResult}`">{{ scope.row.examResult }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="operation" label="操作" fixed="right" width="80">
            <template #default="scope">
              <span class="operation-link">详情</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="tableFooter">
        <div class="left">
          <div class="total">共计: {{ totalSize }} 条</div>
        </div>
        <div class="right">
          <div class="pagination">
            <el-pagination
              layout="prev, pager, next"
              :total="totalSize"
              :page-size="pageSize"
              :current-page="pageNum"
              background
              size="small"
              @current-change="handleSizeChange"
              @size-change="handlePageSizeChange"
            />
          </div>
          <div class="selector">
            <el-select 
              v-model="pageSize" 
              placeholder="每页条数" 
              style="width: 80px;" 
              size="small"
              @change="handlePageSizeChange"
            >
              <el-option label="5条/页" :value="5"></el-option>
              <el-option label="10条/页" :value="10"></el-option>
              <el-option label="20条/页" :value="20"></el-option>
            </el-select>
          </div>
          <div class="jump">
            <span class="title">前往:</span>
            <input 
              type="text" 
              v-model.number="pageNum" 
              @change="handleSizeChange(pageNum)"
              @keyup.enter="handleSizeChange(pageNum)"
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@use "sass:color";
@use ".././fonticon/ScoreOverview/iconfont.css";

// 颜色变量
$primary-color: #4c6fb4;
$danger-color: #eb5757;
$success-color: #4bc65f;
$warning-color: #ff9800;
$info-color: #697ac7;
$gray-color: #909399;
$bg-light: #f1f2f3;
$bg-lighter: #f2f3f5;
$border-color: #e4e7ed;
$text-primary: #000000;
$text-secondary: #86909c;
$text-tertiary: #8e96a0;

.scoreOverviewProceed {
  width: 100%;
  height: calc(100% - 7.5vh);
  display: flex;
  flex-direction: column;
  align-items: center;
  font-weight: 500;
  padding: 20px;
  background-color: #f7f8fa;
  
  .totalData {
    width: 100%;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 20px;
    margin-bottom: 20px;
    
    .layout {
      display: flex;
      justify-content: space-between;
      
      .content {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 10px 0;
        border-right: 1px solid $border-color;
        
        &:last-child {
          border-right: none;
        }
        
        .icon {
          width: 40px;
          height: 40px;
          margin-left: 20px;
          margin-right: 15px;
          text-align: center;
          line-height: 40px;
          border-radius: 50%;
          background-color: #e8f3ff;
          color:#165DFF;
          font-size: 20px;
          transition: all 0.3s ease;
          
          &:hover {
            transform: scale(1.1);
            box-shadow: 0 2px 8px rgba(#165DFF, 0.3);
          }
        }
        
        .text {
          .title {
            font-size: 14px;
            color: $text-secondary;
            margin-bottom: 5px;
          }
          
          .value {
            font-size: 24px;
            font-weight: 600;
            color: $text-primary;
          }
        }
      }
    }
  }
  
  .dataTable {
    width: 100%;
    height: calc(100% - 150px);
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    
    .tableHeader {
      width: 100%;
      height: 60px;
      padding: 0 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid $border-color;
      
      .left {
        width: 250px;
        font-size: 18px;
        font-weight: 600;
        color: $text-primary;
      }
      
      .right {
        width: calc(100% - 250px);
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 15px;
        
        .search {
          width: 20vw;
          height: 36px;
          display: flex;
          align-items: center;
          border-radius: 6px;
          background-color: $bg-light;
          transition: all 0.3s ease;
          
          &:hover {
            background-color: #e0e1e2;
          }
          
          &:focus-within {
            outline: 2px solid $primary-color;
            background-color: #ffffff !important;
            box-shadow: 0 0 0 3px rgba($primary-color, 0.1);
          }
          
          input {
            height: 100%;
            width: 90%;
            outline: none;
            border: none;
            background-color: transparent;
            text-indent: 1em;
            font-size: 14px;
            color: $text-primary;
          }
          
          .icon {
            width: 10%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: $text-tertiary;
            
            &:hover {
              color: $primary-color;
            }
          }
        }
        .export {
          width: 80px;
          height: 36px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          border-radius: 6px;
          background-color: $primary-color;
          font-weight: 500;
          font-size: 14px;
          color: white;
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:hover:not(.export-disabled) {
            background-color: color.adjust($primary-color, $lightness: -5%);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba($primary-color, 0.3);
          }
          
          &:active:not(.export-disabled) {
            transform: translateY(0);
          }
          
          &.export-disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }
        }
      }
    }
    
    .tableContent {
      width: 100%;
      height: calc(100% - 120px);
      padding: 0 20px;
      font-weight: 500;
      
      .status-已完成 {
        color: $success-color;
        font-weight: 600;
      }
      
      .status-进行中 {
        color: $gray-color;
        font-weight: 600;
      }
      
      .result-优秀 {
        color: $info-color;
        font-weight: 600;
      }
      
      .result-合格 {
        color: $success-color;
        font-weight: 600;
      }
      
      .result-不合格 {
        color: $danger-color;
        font-weight: 600;
      }
      
      .operation-link {
        color: $primary-color;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          color: color.adjust($primary-color, $lightness: -10%);
          text-decoration: underline;
        }
      }
    }
    
    .tableFooter {
      width: 100%;
      height: 60px;
      padding: 0 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid $border-color;
      
      .left {
        font-size: 12px;
        color: $text-secondary;
      }
      
      .right {
        display: flex;
        align-items: center;
        gap: 15px;
        
        .jump {
          display: flex;
          align-items: center;
          
          .title {
            margin-right: 5px;
            font-size: 12px;
            color: $text-secondary;
          }
          
          input {
            width: 40px;
            height: 28px;
            text-align: center;
            line-height: 28px;
            border: 1px solid $border-color;
            outline: none;
            border-radius: 4px;
            background-color: #ffffff;
            color: $text-secondary;
            transition: all 0.3s ease;
            
            &:focus {
              border-color: $primary-color;
              color: $text-primary;
              box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .scoreOverviewProceed {
    .dataTable {
      .tableHeader {
        .right {
          .search {
            width: 250px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .scoreOverviewProceed {
    padding: 10px;
    
    .totalData {
      width: 100%;
      
      .layout {
        flex-direction: column;
        
        .content {
          border-right: none;
          border-bottom: 1px solid $border-color;
          justify-content: center;
          
          &:last-child {
            border-bottom: none;
          }
        }
      }
    }
    
    .dataTable {
      width: 100%;
      
      .tableHeader {
        flex-direction: column;
        height: auto;
        padding: 15px;
        gap: 15px;
        
        .left {
          width: 100%;
          text-align: center;
        }
        
        .right {
          width: 100%;
          flex-wrap: wrap;
          justify-content: center;
          
          .search {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>